package old.day20190320.batch;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @author DingZhenYun
 * @create 2019-03-20 20:57
 */
//批量插入
public class Test {
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        String sql=null;
        try{
            connection= JDBCTools.getConnection();
            JDBCTools.bdginTx(connection);
            sql="insert into user values(?,?,?,?)";
            preparedStatement=connection.prepareStatement(sql);
            long begin=System.currentTimeMillis();
            for (int i = 0; i <100000 ; i++) {
                preparedStatement.setInt(1,i+1);
                preparedStatement.setString(2,"name_"+i);
                preparedStatement.setString(3,"password_"+i);
                preparedStatement.setInt(4,i+1);
                //"积攒" SQL
                preparedStatement.addBatch();
                //当 "积攒" 到一定程度, 就统一的执行一次. 并且清空先前 "积攒" 的 SQL
                if((i+1)%300==0){
                    preparedStatement.executeBatch();
                    preparedStatement.clearBatch();
                }
            }
            //若总条数不是批量数值的整数倍, 则还需要再额外的执行一次.
            if(100000%300!=0){
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();
            }
            long end=System.currentTimeMillis();
            System.out.println(end-begin);
            JDBCTools.commit(connection);
        }catch (Exception e){
            e.printStackTrace();
            JDBCTools.rollback(connection);
        }finally {
            JDBCTools.releaseDB(null,preparedStatement,connection);
        }
    }
}
